layui.use(['table', 'form', 'jquery', 'laydate', 'layer'], function () {
    let table = layui.table;
    let layer = layui.layer;
    let form = layui.form;
    let laydate = layui.laydate;

    let BIZ_NAME = 'member';
    let BIZ_TABLE = 'member-table';
    let BIZ_FORM = 'member-form';
    let tableMemberObj;
    let formMemberObj;

    //日期
    laydate.render({
        elem: '#birthday'
    });

    let cols = [
        [
            {type: 'checkbox'},
            {title: '会员id', field: 'id', align: 'center', width: 80},
            {title: '姓名', field: 'name', align: 'center', width: 120},
            {title: '手机', field: 'mobile', align: 'center', width: 120},
            {title: '充值余额', field: 'rechargeBalance', align: 'center', width: 100, color: 'green'},
            {title: '赠送余额', field: 'giftBalance', align: 'center', width: 100, color: 'blue'},
            {title: '充值次数', field: 'times', align: 'center', width: 100, color: 'blue'},
            {title: '性别', field: 'sex', align: 'center', width: 80},
            {title: '生日', field: 'birthday', align: 'center', width: 160},
            {title: '注册日期', field: 'registrationDate', align: 'center', width: 120},
            {title: '会员类型', field: 'memberType', align: 'center', width: 120},
            {title: '会员积分', field: 'integral', align: 'center', width: 100},
            {title: '客户经理', field: 'accountManager', align: 'center', width: 120},
            {title: '地址', field: 'address', align: 'center', width: 120},
            {title: '创建时间', field: 'time', align: 'center', width: 120},
            {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 275}
        ]
    ]

    /*数据列表加载*/
    tableMemberObj = table.render({
        elem: '#' + BIZ_TABLE,
        url: '/' + BIZ_NAME + '/page',
        text: {none: '暂无相关数据'},
        response: {
            statusCode: 200,
            msgName: 'message'
        },
        page: true,
        limit: 15,
        limits: [20, 40, 50],
        cols: cols,
        skin: 'line',
        toolbar: '#toolbarList', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            title: '提示'
            , layEvent: 'LAYTABLE_TIPS'
            , icon: 'layui-icon-tips'
        }],
        done: function (res, curr, count) {
            let data = res.data;
            let that = this.elem.next();
            $.each(data, function (i, e) {
                if((e.times === 0 || !e.times) && (e.rechargeBalance === 0 || !e.rechargeBalance)){
                    let tr = that.find(".layui-table-box tbody tr[data-index='" + i + "']");
                    tr.css("color", "red");
                }
            });
        },
        id: 'member-table'
    });

    //顶部工具栏事件
    table.on('toolbar(member-table)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'addMember'://添加会员
                window.memberForm();
                break;

            //自定义头工具栏右侧图标 - 提示
            case 'LAYTABLE_TIPS':
                layer.alert('这是工具栏右侧自定义的一个图标按钮');
                break
            case 'fitConsumption':
                window.fitConsumptionRecordsForm();
                break;
            case 'refund':
                if (checkStatus.data.length <= 0 || checkStatus.data.length > 1) {
                    layer.alert('请选择一条数据!', {icon: 2});
                    return;
                }
                window.refund(checkStatus.data[0]);
                break;
        }
    });

    //操作栏事件
    table.on('tool(member-table)', function (obj) {
        if (obj.event === 'remove') {
            window.removeMember(obj);
        } else if (obj.event === 'edit') {
            window.memberForm(obj);
        } else if (obj.event === 'recharge') {//会员充值
            window.rechargeRecordForm(obj.data);
        } else if (obj.event === 'consumption') {//会员消费
            window.consumptionRecordsForm(obj.data)
        } else if (obj.event === 'rechargeTimes') {//会员充次
            window.rechargeTimesForm(obj.data);
        }
    });

    // 监听搜索
    let $ = layui.$, active = {
        reset: function () {
            $('#memberId').val('');
            $('#name').val('');
            $('#mobile').val('');
        },
        reload: function () {
            let id = $('#memberId');
            let name = $('#name');
            let mobile = $('#mobile');

            //执行重载
            table.reload('member-table', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , where: {
                    id: id.val(),
                    nameLike: name.val(),
                    mobileLike: mobile.val()
                }
            });
        }
    };

    /*检索栏按钮 点击事件监控*/
    $('.memberTable .layui-btn').on('click', function () {
        let type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    /*新增 、编辑会员按钮事件 */
    window.memberForm = function (obj) {
        let title;
        if (obj) {
            title = '修改信息';
        } else {
            title = '新增会员';
        }
        formMemberObj = layer.open({
            type: 1,
            title: title,
            shade: 0.1,
            area: ['60%', '98%'],
            btn: ['立即提交', '取消'],
            yes: function (index, layero) {
                $('#' + BIZ_FORM + ' [lay-submit]').click();
            },
            cancel: function (index, layero) {
                layer.close(index);
            },
            content: $('#' + BIZ_FORM),
            success: function (layero, index) {
                if (obj) {
                    // 修改时填充数据
                    form.val(BIZ_FORM, obj.data);
                } else {
                    // 新增时清空表单
                    form.val(BIZ_FORM, {});
                    $('#id').val('');
                    $('#memberFormReset').click();
                }
            }
        });
    }

    /*删除按钮事件*/
    window.removeMember = function (obj) {
        layer.confirm('确定要删除', {icon: 3, title: '提示'}, function (index) {
            layer.close(index);
            $.ajax({
                url: "/" + BIZ_NAME + "/remove/" + obj.data['id'],
                type: 'DELETE',
                success: function (result) {
                    if (result.code === 200) {
                        layer.msg(result.message, {icon: 1, time: 1000}, function () {
                            obj.del();
                        });
                        tableMemberObj.reload();
                    } else {
                        layer.alert(result.message, {icon: 2});
                    }
                }
            })
        });
    }

    //会员退费
    window.refund = function (obj) {
        layer.confirm('账户余额为：' + obj.rechargeBalance + '，确定要退费?', {icon: 3, title: '提示'}, function (index) {
            layer.close(index);
            $.ajax({
                url: "/" + BIZ_NAME + "/refund/" + obj.id,
                type: 'POST',
                success: function (result) {
                    if (result.code === 200) {
                        layer.msg(result.message, {icon: 1, time: 1000});
                        tableMemberObj.reload();
                    }
                }
            });
        });
    }

    /*提交按钮事件*/
    form.on('submit(' + BIZ_FORM + ')', function (data) {
        let url = '/save';
        let type = 'POST';

        //如果id不为空则调用修改接口
        if (data.field.id) {
            url = '/update'
            type = 'POST';
        }
        let currentUser = $('#createUser').text();
        data.field.createBy = currentUser;
        data.field.modifiedBy = currentUser;
        $.ajax({
            url: '/' + BIZ_NAME + url,
            data: JSON.stringify(data.field),
            type: type,
            dataType: 'json',
            contentType: 'application/json',
            success: function (result) {
                if (result.code === 200) {
                    layer.msg(result.message, {icon: 1, time: 1000}, function () {
                        tableMemberObj.reload();
                        layer.close(formMemberObj);
                    });
                } else {
                    layer.alert(result.message, {icon: 2});
                }
            }
        })
        return false;
    });

    //监听表格行双击事件（单击事件为：row）
    table.on('rowDouble(member-table)', function (obj) {
        let data = obj.data;
        formMemberObj = layer.open({
            type: 1,
            title: '查看',
            shade: 0.1,
            area: ['60%', '98%'],
            btn: ['关闭'],
            close: function (index, layero) {
                layer.close(index);
            },
            content: $('#read-only-member-form'),
            success: function (layero, index) {
                if (obj) {
                    // 填充数据
                    form.val('read-only-member-form', obj.data);
                }
            }
        });

        let where = {"memberId": obj.data['id']}
        //充值记录列表
        window.renderRechargeRecordTable(where);
        //消费记录列表
        window.renderConsumptionRecordsTable(where);
        //充次记录列表
        window.renderRechargeTimesTable(where);
        //计次消费列表
        window.renderConsumptionTimesTable(where)

        //标注选中样式
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });
});